﻿using DataBaseSync.Components;
using DataBaseSync.Vendor.SyncTask;
using System.IO;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using DataBaseSync.Vendor.Log;
using System.Windows.Documents;
using System.Windows.Media;
using System;
using System.Diagnostics;

namespace DataBaseSync.Pages
{
    /// <summary>
    /// PageTask.xaml 的交互逻辑
    /// </summary>
    public partial class PageTask : Page, INotifyPropertyChanged
    {
        public List<ITask> tasks = new List<ITask>();

        public event PropertyChangedEventHandler? PropertyChanged;
        public Logger? logger;
        public bool isrunning { get; set; } = true;
        protected SolidColorBrush _txtcolor = new SolidColorBrush(Color.FromArgb(255, 0x7e, 0x7e, 0x7e));
        public int TimeInterval { get; set; } = 300;
        public int _time {
            get; set;
        }
        public int _timewait = 0;
        public PageTask(Logger _logger)
        {

            InitializeComponent();
            //日志记录器：实现匿名函数
            logger = _logger;
            logger.Record = (str) =>
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    Paragraph p = new Paragraph();
                    p.Foreground = _txtcolor;
                    p.Inlines.Add(new Run(str));
                    richtbxflowdoc.Blocks.Add(p);
                    richtbx.ScrollToEnd();

                }));
            };
            
            logger.Save = () =>
            {
                logger.path = $"D:/LogFile/DataBaseSync/{DateTime.Now.ToString("yyyy")}";
                if (!Directory.Exists(logger.path))
                    Directory.CreateDirectory(logger.path);
                logger.path += $"/{DateTime.Now.ToString("yyyy-MM-dd")}.txt";
                try
                {
                    using (FileStream fs = new FileStream(logger.path, FileMode.Append,FileAccess.Write))
                    {
                        using (StreamWriter writter = new StreamWriter(fs))
                        {
                            writter.WriteLine(new TextRange(richtbxflowdoc.ContentStart, richtbxflowdoc.ContentEnd).Text);
                        }
                    }
                }
                catch (Exception)
                {
                    logger.Record(logger.path);
                    logger.Record("日志保存失败");
                }
            };
            //设置上下文
            this.DataContext = this;

            _time = TimeInterval;
            OnPropertyChanged("_time");
            MainTask();
        }
        /// <summary>
        /// 从本地获取Json
        /// </summary>
        /// <returns></returns>
        public void LoadConfiguration()
        {
            this.Dispatcher.Invoke(() =>
            {
                
                tasks.Add(new TaskDownloadMESCarInfo(logger)
                {
                    Name = "下载车辆信息"
                });
                tasks.Add(new TaskDownloadMESWareInfo(logger)
                {
                    Name = "下载ECU件号信息"
                });
            });
        }
        /// <summary>
        /// 数据同步主函数
        /// </summary>
        /// <returns></returns>
        public void MainTask()
        {
            LoadConfiguration();
            this.Dispatcher.Invoke(new Action(() =>
            {
                Task.Run(() =>
                {
                    //绑定item控件到页面上
                    BandTaskItems(tasks);
                    Stopwatch _watch = Stopwatch.StartNew();
                    while (true)
                    {
                        if (isrunning)
                        {
                            if (_time <= 0)
                            {
                                BeforeInvoke();

                                tasks.ForEach(task =>
                                {
                                    task.Complate = 0;
                                    task.Invoke();
                                });


                                AfterInvoke();
                                _watch.Restart();
                            }
                            else //没有到执行任务的时间，更新前台计时器
                            {
                                UpdateTimer((int)_watch.ElapsedMilliseconds);
                            }
                        }
                        else
                        {
                            _timewait = ((int)_watch.ElapsedMilliseconds / 1000)- (TimeInterval- _time);
                           
                        }
                        Task.Delay(100).Wait();


                    }
                });

            }));
        }
        /// <summary>
        /// 数据
        /// </summary>
        /// <param name="member"></param>
        public void OnPropertyChanged([CallerMemberName] string member = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(member));
        }
        public void UpdateTimer(int time)
        {
            this.Dispatcher.Invoke(() =>
            {
               
                _time = TimeInterval-(time / 1000)+ _timewait;
               
                OnPropertyChanged("_time");
            });
        }
        /// <summary>
        /// 绑定控件
        /// </summary>
        /// <param name="_uttasks"></param>
        public void BandTaskItems(List<ITask> _uttasks)
        {

            this.Dispatcher.Invoke(() =>
            {
                TaskListCtn.Children.Clear();

                for (int i = 0; i < _uttasks.Count; i++)
                {
                    _uttasks[i]._CusTaskProgress.TaskName = _uttasks[i].Name;
                    _uttasks[i]._CusTaskProgress.complate = 0;
                    _uttasks[i]._CusTaskProgress.total = _uttasks[i].Total;

                    _uttasks[i].UpdateProgress = UpdateProgress;
                    _uttasks[i].BeforeInvoke = CusUpdateUI;
                    TaskListCtn.Children.Add(_uttasks[i]._CusTaskProgress);
                }

            });
        }
        /// <summary>
        /// 向外部暴露配置方法，以便其他页面配置
        /// </summary>
        public void UpdateTasks()
        {

        }
        public void BeforeInvoke()
        {
            this.Dispatcher.Invoke(() =>
            {
                _timewait = 0;
                _time = TimeInterval;
                OnPropertyChanged("_time");

                richtbxflowdoc.Blocks.Clear();
                logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":开始同步");
            });
        }
        public void AfterInvoke()
        {
            this.Dispatcher?.Invoke(() =>
            {
                
                logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":结束同步");
                logger.Save();
                GC.Collect();
            });
        }
        public void CusUpdateUI(CusTaskProgress _ctp,string taskname, int total)
        {
            this.Dispatcher.Invoke(() => 
            {
                _ctp.total = total;
                _ctp.TaskName = taskname;
            });
        }
        public void UpdateProgress(CusTaskProgress _ctp,int _complate)
        {
            this.Dispatcher.Invoke(() =>
            {
                
                _ctp.complate = _complate;
                
                _ctp.Value = _ctp.total == 0 ? 100 : (_complate*100) / _ctp.total;
            });
        }

        private void btnrun_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            
            if (!isrunning)
            {
                this.btnrun.Foreground=Brushes.Red;
                logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":继续同步");
            }

            else
            {
                logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":暂停同步");
                _timewait = 0;
                 this.btnrun.Foreground = Brushes.Green;
            }

            tasks.ForEach(task =>
            {
                task.IsRunning = !task.IsRunning;
            });
            isrunning = !isrunning;
            //this.btnrun.IsEnabled = false;

        }

        private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            
            //if (OracleService.Connect() == 0)
            //    logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":连接Oracle成功");
            //else
            //{
            //    logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":连接Oracle失败");
            //    return;
            //}
            //if (MysqlService.Connect() == 0)
            //    logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":连接Mysql成功");
            //else
            //    logger.Record(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":连接Mysql失败");
        }
    }
    
}
